package com.cino.demos.controller.file;

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;

@Controller
public class FileController {

    // 定义我们存放文件的"仓库"路径
    // "classpath:static/" 是一个特殊路径，指向 src/main/resources/static
    private final Path fileStorageLocation = Paths.get("src/main/resources/static");

    @GetMapping("/download/{filename:.+}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String filename) {
        System.out.println("Spring Boot 收到下载请求，文件名: " + filename);

        try {
            // 1. 构造文件的完整路径
            Path filePath = this.fileStorageLocation.resolve(filename).normalize();

            // 2. 将文件路径包装成一个 Spring 的 Resource 对象
            //    Resource 是Spring对所有可读资源（文件、URL等）的高级抽象
            Resource resource = new UrlResource(filePath.toUri());

            if (resource.exists()) {
                System.out.println("文件找到，准备开始下载...");

                // 3. 返回一个 ResponseEntity，把 Resource 作为响应体
                //    Spring 框架会在这里接管一切！
                //    它会自动从 Resource 中获取 InputStream，
                //    然后用最高效的方式把流写入到HTTP响应中。
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                        .body(resource);
            } else {
                System.out.println("文件未找到！");
                return ResponseEntity.notFound().build();
            }
        } catch (MalformedURLException ex) {
            return ResponseEntity.badRequest().build();
        }
    }
}